import { RdbPredicateWrapper } from './RdbPredicateWrapper'
import { Column, ColumnType } from '../schema/Column'
import { relationalStore } from '@kit.ArkData'
import { Database } from '../schema/Database'
import { Dao } from '../schema/Dao'
import { QuerySQL } from './SQL'

/**
 * 用于匹配指定类型的构造函数
 */
export type Constructor<T> = new (...args: any[]) => T

/**
 * 定义条件查询的作用域函数类型，用于链式构建查询条件
 */
export type RdbPredicateScope<M> = (it: RdbPredicateWrapper<M>) => RdbPredicateWrapper<M>

/**
 * 从 Column 类型中提取对应的模型字段名
 */
type ExtractColumnKey<T extends ColumnType> = T extends Column<any, infer M, any, any> ? M extends string ? M : never : never

/**
 * 根据提供的 Column 类型数组，从模型 M 中提取对应字段组成新的类型
 */
export type PickModelType<M, T extends ColumnType[]> = T['length'] extends 0 ? M : Pick<M, ExtractColumnKey<T[number]>>

/**
 * 支持的数据源类型
 */
export type DatabaseSource = relationalStore.RdbStore | Database | Dao

/**
 * SQL 查询的返回类型
 */
export type SqlReturnType<T extends QuerySQL<any>> = T extends QuerySQL<infer E> ? E extends [] ? never : ExtractObject<E> : never

type ExtractObject<T extends any[], Result = {}> =
  T extends [infer First, ...infer Rest]
    ? First extends Column<infer Name, any, infer Type, any>
    ? ExtractObject<Rest, Result & { [K in Name]: Type }>
    : never
    : { [K in keyof Result]: Result[K] }